import { createApp, reactive, getCurrentInstance } from "vue";

import CommonAlert from "./common-alert.vue";

const extend = Object.assign;

function usePopupState() {
  const state = reactive({
    show: false,
  });

  const toggle = (show) => {
    state.show = show;
  };

  const open = (props) => {
    extend(state, props);
    toggle(true);
  };

  const close = () => toggle(false);

  return {
    open,
    close,
    state,
    toggle,
  };
}

function createInstance() {
  const { instance, unmount } = mountComponent({
    setup() {
      // const message = ref('');
      const { open, state, close, toggle } = usePopupState();

      const onClosed = () => {
        unmount();
      };

      const render = () => {
        const attrs = {
          onClosed,
          'onUpdate:show': toggle,
        };
        return <CommonAlert {...state} {...attrs} />;
      };

      // support dynamic modification of message
      // watch(message, (val) => {
      //   state.message = val;
      // });

      // rewrite render function
      getCurrentInstance().render = render;

      return {
        open,
        close,
        // message,
      };
    },
  });

  return instance;
}

function mountComponent(rootComponent) {
  const app = createApp(rootComponent);
  const root = document.createElement("div");
  document.body.appendChild(root);
  return {
    instance: app.mount(root),
    unmount() {
      app.unmount();
      document.body.removeChild(root);
    },
  };
}

function useComponent(options) {
  const commonalert = createInstance();
  if (typeof options !== "object") {
    return;
  }
  commonalert.open(extend({}, options));
  return commonalert;
}

export default useComponent
